/*
 * @Author: N0ts
 * @Date: 2021-10-20 11:31:16
 * @LastEditTime: 2021-10-21 10:50:56
 * @Description: 私钥
 * @FilePath: /Web/js/hooks/access.js
 * @Mail：mail@n0ts.cn
 */

const { reactive, toRefs } = Vue;
import $api from "../api.js";
import notify from "./notify.js";

let data = reactive({
    accessData: null // 私钥数据
});

export default function access() {
    /**
     * 获取私钥数据
     */
    function getAccess() {
        axios.get($api.AccessTokenGet).then((res) => {
            if (!res || res.code == 0) {
                return notify(res.message, "error");
            }

            data.accessData = res.data[0] ?? { accessToken1: "" };
        });
    }
    /**
     * 新增 & 修改私钥
     */
    function accessSave(id) {
        if (data.accessData.accessToken1 == "") {
            return notify("不能保存空数据哦", "warning");
        }

        // 新增 修改判断
        let url = id ? $api.AccessTokenUpdate : $api.AccessTokenAdd;
        let method = id ? "patch" : "post";

        axios({
            url,
            method,
            data: {
                id,
                accessToken1: data.accessData.accessToken1,
                alias: "暂无"
            }
        }).then((res) => {
            if (!res || res.code == 0) {
                return notify(res.message, "error");
            }

            notify(res.message, "success");

            // 如果是新增则重新加载数据
            if(!id) {
                getAccess();
            }
        });
    }

    /**
     * 删除私钥
     */
    function accessDel(id) {
        if (!id) {
            return notify("请设置后在删除哦", "warning");
        }

        axios
            .delete($api.AccessTokenDelete, {
                params: {
                    id
                }
            })
            .then((res) => {
                if (!res || res.code == 0) {
                    return notify(res.message, "error");
                }

                notify(res.message, "success");
                data.accessData = { accessToken1: "" };
            });
    }

    return {
        ...toRefs(data),
        getAccess,
        accessSave,
        accessDel
    };
}
